package com.dog.basics.netty.util;


import cn.hutool.core.util.ObjectUtil;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存储通道信息
 */
@SuppressWarnings("ALL")
public class SessionSocketHolder {
    private static final ConcurrentHashMap<Long, NioSocketChannel> CHANNEL_MAP = new ConcurrentHashMap<>(16);
    private static final ConcurrentHashMap<String,Long> SESSION_MAP = new ConcurrentHashMap<>(16);

    public static void saveSession(String channelId,Long equipmentId){
        SESSION_MAP.put(channelId,equipmentId);
    }

    public static void removeSession(String channelId){
        SESSION_MAP.remove(channelId) ;
    }

	public static Long getSession(String channelId){
        return SESSION_MAP.get(channelId) ;
    }

    public static void put(Long id, NioSocketChannel socketChannel) {
        CHANNEL_MAP.put(id, socketChannel);
    }

    public static NioSocketChannel get(Long id) {
        return CHANNEL_MAP.get(id);
    }


	public static Map<Long, NioSocketChannel> getMap() {
        return CHANNEL_MAP;
    }
	public static void remove(Long key) {
		CHANNEL_MAP.remove(key);
	}
    public static void remove(NioSocketChannel nioSocketChannel) {
        CHANNEL_MAP.entrySet().stream().filter(entry -> entry.getValue() == nioSocketChannel).forEach(entry -> CHANNEL_MAP.remove(entry.getKey()));
    }


	/**
	 * 便携删除所有
	 * @param channelId
	 */
	public static void logu(String channelId){
		Long key = SESSION_MAP.get(channelId);
		if (ObjectUtil.isNotNull(key)) {
			CHANNEL_MAP.remove(key);
			SESSION_MAP.remove(channelId);
		}
	}

	public static void logu(Long key){
		NioSocketChannel nioSocketChannel = CHANNEL_MAP.get(key);
		if (ObjectUtil.isNotNull(key)) {
			CHANNEL_MAP.remove(key);
			if (ObjectUtil.isNotNull(nioSocketChannel)) {
				SESSION_MAP.remove(nioSocketChannel.id().asLongText());
			}
		}
	}

	/**
	 * 便携添加所有的、
	 * @param key
	 * @param socketChannel
	 */
	public static void addAll(Long key,NioSocketChannel socketChannel) {
		CHANNEL_MAP.put(key, socketChannel);
		SESSION_MAP.put(socketChannel.id().asLongText(),key);
	}

}
